const { exec } = require('../db/mysql')

// 获取文章列表
const getBlogList = params => {
  const { keyword, time } = params || {}
  let sql = `select id, createTime, classify, title, description from blog where 1=1 `
  if (keyword) {
    sql += `and title like '%${keyword}%' `
  }
  if (time) {
    sql += `and createTime like '%${time}%' `
  }
  sql += 'order by createTime desc'
  return exec(sql)
}

// 获取文章详情
const getBlogDetail = params => {
  const { id } = params
  let sql = `select * from blog where id='${id}'`
  return exec(sql)
}

// 新建文章
const createBlog = blogData => {
  let { title, content, classify, tags, imgUrl, description } = blogData
  content = content.replace(/'/g, '"')
  tags = tags.length ? tags.join(',') : ''
  imgUrl = imgUrl || ''
  description = description || ''
  const createTime = new Date().getTime()
  let sql = `insert into blog (title, content, classify, createTime, tags, imgUrl, description) values ('${title}', '${content}', '${classify}', '${createTime}', '${tags}', '${imgUrl}', '${description}')`
  return exec(sql)
}

// 更新文章
const updateBlog = blogData => {
  let { id, title, content, classify, tags, imgUrl, description } = blogData
  content = content.replace(/'/g, '"')
  tags = tags.length ? tags.join(',') : ''
  imgUrl = imgUrl || ''
  description = description || ''
  const createTime = new Date().getTime()
  let sql = `update blog set title='${title}', content='${content}', createTime='${createTime}', classify='${classify}', tags='${tags}', imgUrl='${imgUrl}', description='${description}' where id='${id}'`
  return exec(sql).then(data => {
    if (data.affectedRows > 0) {
      return true
    } else {
      return false
    }
  })
}

// 删除文章
const deleteBlog = blogData => {
  const { id } = blogData
  let sql = `delete from blog where id='${id}'`
  return exec(sql).then(data => {
    if (data.affectedRows > 0) {
      return true
    } else {
      return false
    }
  })
}

module.exports = {
  getBlogList,
  getBlogDetail,
  createBlog,
  updateBlog,
  deleteBlog
}
